const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { UserModel } = require('../models');
const config = require('../config/config');
const { toSeconds } = require('../utils/transform');

class AuthService {
  constructor() {
    this.userModel = UserModel; // 使用静态模型方法，无需实例化
    // JWT配置
    this.jwtSecret = config.jwt.secret;
    this.jwtExpiresIn = config.jwt.expiresIn;
  }

  // 登录服务
  async login(username, password) {
    try {
      // 验证参数
      if (!username || !password) {
        return {
          success: false,
          message: '用户名和密码不能为空',
          status: 400
        };
      }

      // 查询用户（使用静态模型）
      const user = await this.userModel.getUserByUsername(username);

      if (!user) {
        return {
          success: false,
          message: '用户名或密码错误',
          status: 401
        };
      }

      // 验证密码
      const passwordMatch = await bcrypt.compare(password, user.password);
      if (!passwordMatch) {
        return {
          success: false,
          message: '用户名或密码错误',
          status: 401
        };
      }

      // 生成JWT
      const scope = user.type === 1 ? ['read', 'write'] : ['read'];
      console.log('[AuthService] login scope resolved:', { username, type: user.type, scope });
      const token = jwt.sign(
        {
          userId: user.id,
          username: user.username,
          type: user.type,
          scope
        },
        this.jwtSecret,
        {
          expiresIn: this.jwtExpiresIn
        }
      );

      const refreshToken = jwt.sign(
        {
          userId: user.id,
          username: user.username
        },
        this.jwtSecret,
        {
          expiresIn: '7d' // 刷新令牌有效期通常较长
        }
      );

      return {
        success: true,
        data: {
          access_token: token,
          refresh_token: refreshToken,
          expires_in: toSeconds(this.jwtExpiresIn),
          token_type: 'Bearer',
          scope: Array.isArray(scope) ? scope.join(' ') : String(scope || ''),
          scopes: Array.isArray(scope) ? scope : (scope ? String(scope).split(/\s+/).filter(Boolean) : []),
          info: {
            userId: user.id,
            username: user.username,
            type: user.type,
            organizationId: user.organization_id,
            nickname: user.nickname,
            avatar: user.avatar
          },
          attributes: {
            permissions: Array.isArray(scope) ? scope : (scope ? String(scope).split(/\s+/).filter(Boolean) : []),
            roleCodes: user.type === 1 ? ['admin'] : ['user']
          }
        },
        message: '登录成功'
      };
    } catch (error) {
      console.error('登录服务错误:', error);
      return {
        success: false,
        error: error.message,
        message: '登录失败，请稍后重试',
        status: 500
      };
    }
  }

  // 刷新令牌服务
  async refreshToken(refreshToken) {
    try {
      // 验证参数
      if (!refreshToken) {
        return {
          success: false,
          message: '刷新令牌不能为空',
          status: 400
        };
      }

      // 验证刷新令牌
      const decoded = jwt.verify(refreshToken, this.jwtSecret);
      
      // 查询用户（使用静态模型）
      const user = await this.userModel.getUserById(decoded.userId);
      
      if (!user) {
        return {
          success: false,
          message: '用户不存在',
          status: 401
        };
      }

      // 生成新的访问令牌
      const newScope = user.type === 1 ? ['read', 'write'] : ['read'];
      console.log('[AuthService] refresh scope resolved:', { userId: user.id, type: user.type, scope: newScope });
      const newToken = jwt.sign(
        {
          userId: user.id,
          username: user.username,
          type: user.type,
          scope: newScope
        },
        this.jwtSecret,
        {
          expiresIn: this.jwtExpiresIn
        }
      );

      return {
        success: true,
        data: {
          access_token: newToken,
          expires_in: toSeconds(this.jwtExpiresIn),
          token_type: 'Bearer',
          scope: Array.isArray(newScope) ? newScope.join(' ') : String(newScope || ''),
          scopes: Array.isArray(newScope) ? newScope : (newScope ? String(newScope).split(/\s+/).filter(Boolean) : [])
        },
        message: '令牌刷新成功'
      };
    } catch (error) {
      console.error('刷新令牌服务错误:', error);
      return {
        success: false,
        error: error.message,
        message: '刷新令牌无效或已过期',
        status: 401
      };
    }
  }

  // 登出服务
  async logout() {
    try {
      // 实际项目中可能需要实现令牌黑名单等功能
      return {
        success: true,
        message: '登出成功'
      };
    } catch (error) {
      console.error('登出服务错误:', error);
      return {
        success: false,
        error: error.message,
        message: '登出失败，请稍后重试',
        status: 500
      };
    }
  }
}

module.exports = AuthService;